﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace PC.AzureMultiApp.Core.Helpers
{
    public static class Commands
    {
        public static bool LaunchUnistallCmdIfExists(string applicationPath)
        {
            return LaunchCmdIfExists(applicationPath, "uninstall.cmd", true) 
                    && LaunchCmdIfExists(Path.Combine(applicationPath, "bin"), "uninstall.cmd", true);
        }

        public static bool LaunchBeforeCmdIfExists(string applicationPath)
        {
            return LaunchCmdIfExists(applicationPath, "before.cmd", true) 
                    && LaunchCmdIfExists(Path.Combine(applicationPath, "bin"), "before.cmd", true);
        }

        public static bool LaunchAfterAndWaitCmdIfExists(string applicationPath)
        {
            return LaunchCmdIfExists(applicationPath, "setup.cmd", true) 
                    && LaunchCmdIfExists(Path.Combine(applicationPath, "bin"), "setup.cmd", true);
        }

        public static bool LaunchAfterAndNoWaitCmdIfExists(string applicationPath)
        {
            return LaunchCmdIfExists(applicationPath, "after.cmd", false)
                && LaunchCmdIfExists(Path.Combine(applicationPath, "bin"), "after.cmd", false);
        }

        private static bool LaunchCmdIfExists(string applicationPath, string filename, bool wait)
        {
            bool result = false;
            try
            {
                if (Directory.Exists(applicationPath))
                {
                    string command = Directory.GetFiles(applicationPath, filename).FirstOrDefault();

                    if (!String.IsNullOrEmpty(command))
                    {
                        Trace.WriteLine("LaunchCmdIfExists" + command, "Information");

                        ProcessStartInfo info = new ProcessStartInfo()
                        {
                            WorkingDirectory = Path.GetDirectoryName(command),
                            Arguments = String.Format("/c {0}", command),
                            FileName = "cmd.exe"
                        };

                        Process p = Process.Start(info);

                        if (wait)
                            p.WaitForExit();
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message, "Error");
            }

            return result;
        }
    }
}
